#include "contactlistmanager.h"

ContactListManager::ContactListManager(QListWidget *contactList)
{
    this->contactList = contactList;
    this->publicContacts = new QVector<PublicContact *>::QVector();
    this->officialy_online = false;
}

void ContactListManager::newPublicIdentityPacket(QString alias, int port, QHostAddress ip)
{
    int number_of_alias = 0;
    bool is_in = false;
    int i;
    for (i = 0; i < this->publicContacts->size(); i++)
    {
        if (this->publicContacts->value(i)->getIp() == ip)
        {
            number_of_alias++;
            if (this->publicContacts->value(i)->getPort() == port) {
                is_in = true;
                this->publicContacts->value(i)->newIdentityPacket(alias);
            }
        }
    }
    if ((number_of_alias < ContactListManager::max_alias_per_ip) &&
        (!is_in)) {
        this->publicContacts->append(new PublicContact::PublicContact(alias, port, ip));
    }
}

void ContactListManager::endOfBroadcastScan()
{
    int i;
    for (i = 0; i < this->publicContacts->size(); i++)
    {
        this->publicContacts->value(i)->update();
        if (this->publicContacts->value(i)->getInactiveTime() >
            ContactListManager::broadcast_maxtime)
        {
            this->publicContacts->remove(i);
        }
    }
}

void ContactListManager::updateUi()
{
    int i;
    this->contactList->clear();
    // Add first private contacts
    for (i = 0; i < this->publicContacts->size(); i++)
    {
        new QListWidgetItem::QListWidgetItem(QIcon(":/images/mverde.png"),
                                             this->publicContacts->value(i)->getAlias(),
                                             this->contactList);
    }
}

void ContactListManager::startConversation(int row)
{
    if ((this->officialy_online) && (row >= 0)) { // replace 0 for number of private contacts
        this->publicContacts->value(row)->startConversation();
    }
}

ContactListManager::~ContactListManager()
{
    int i;
    for (i = 0; i < this->publicContacts->size(); i++)
    {
        delete this->publicContacts->value(i);
    }
    delete this->publicContacts;
}
